package com.ruoyi.kiku.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.tt.WeiboSupetopicSigner;
import com.ruoyi.kiku.domain.MySuperWords;
import com.ruoyi.kiku.service.IMySuperWordsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author: TT
 * @Date: 2025/8/20 9:54
 * @Description: 我的超话服务类
 * @Version: v1.0
 */
@Service
public class MySuperWordsServiceImpl implements IMySuperWordsService {

    private final RedisCache redisCache;

    public MySuperWordsServiceImpl(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    /**
     * 根据微博的cookie获取我的超话
     * @return  List<MySuperWords>
     */
    @Override
    public List<MySuperWords> selectMySuperWordsList() {
        Long userId = SecurityUtils.getUserId();
        String redisCookie = redisCache.getCacheObject("0_cookie:" + userId);
        WeiboSupetopicSigner superTopicSigner = new WeiboSupetopicSigner(redisCookie);
        List<JSONObject> superTopicList = new ArrayList<>();
        try {
            superTopicList = superTopicSigner.getSuperTopicList();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        List<MySuperWords> mySuperWords = new ArrayList<>();
        if (!superTopicList.isEmpty()){
            mySuperWords= JsonUtils.convert(superTopicList, MySuperWords.class);
            // 截取集合中oid的值“:”后面的
            for (MySuperWords mySuperWord : mySuperWords) {
                mySuperWord.setOid(mySuperWord.getOid().substring(mySuperWord.getOid().indexOf(":") + 1));
            }
        }
        Boolean allSignFlag = redisCache.getCacheObject("topicIfSign: all");
        if (allSignFlag != null){
            mySuperWords.forEach(mySuperWord -> mySuperWord.setIfSign(allSignFlag));
        }else {
            for (int i = 0; i < mySuperWords.size(); i++) {
                String topicId = mySuperWords.get(i).getOid();
                System.out.println(topicId);
                Boolean signFlag = redisCache.getCacheObject("topicIfSign: " + topicId);
                if (signFlag != null){
                    mySuperWords.get(i).setIfSign(signFlag);
                }else {
                    mySuperWords.get(i).setIfSign(false);
                }

            }
        }
        return mySuperWords;
    }

    /**
     * 根据微博的cookie和超话id和超话名称进行超话签到
     * @param topicId 超话id
     * @param topicName 超话名称
     * @return String
     */
    @Override
    public String mySuperTopicSign( String topicId, String topicName) {
        Long userId = SecurityUtils.getUserId();
        String redisCookie = redisCache.getCacheObject("0_cookie:" + userId);
        WeiboSupetopicSigner superTopicSigner = new WeiboSupetopicSigner(redisCookie);
        Boolean b = false;
        try {
             b = superTopicSigner.signSuperTopic(topicId, topicName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 设置缓存并指定过期时间
        redisCache.setCacheObject("topicIfSign: " + topicId,true, DateUtils.getNowToMorningSecond(), TimeUnit.SECONDS);
        return b ? "【"+topicName+"】超话，签到成功" : "【"+topicName+"】超话，小橘子今天已经签到了哦";
    }
    /**
     * 根据微博的cookie进行批量超话签到
     * @return List<String>
     */
    @Override
    public List<String> mySuperTopicBatchSign() {
        Long userId = SecurityUtils.getUserId();
        String redisCookie = redisCache.getCacheObject("0_cookie:" + userId);
        WeiboSupetopicSigner superTopicSigner = new WeiboSupetopicSigner(redisCookie);
        List<String> result = new ArrayList<>();
        try {
             result = superTopicSigner.autoSignAllTopicsWithResults();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        redisCache.setCacheObject("topicIfSign: all",true,DateUtils.getNowToMorningSecond(), TimeUnit.SECONDS);
        return result;
    }

    /**
     * 验证微博cookie
     * @return String
     */
    @Override
    public Integer verifyWeiboCookie() {
        Long userId = SecurityUtils.getUserId();
        String cookie = redisCache.getCacheObject("0_cookie:" + userId);
        if (cookie== null ||cookie.isEmpty()){
            return 5000;
        }else{
            return 618;
        }
    }
    /**
     * 设置微博cookie
     * @param cookie  token
     */
    @Override
    public void setWeiboCookie(String cookie) {
        Long userId = SecurityUtils.getUserId();
        redisCache.setCacheObject("0_cookie:" + userId, cookie);
        redisCache.expire("0_cookie:" + userId, 7 * 24 * 60 * 60);
    }
    /**
     * 删除所有用户的微博cookie
     */
    @Override
    public void removeAllWeiboCookie() {
        // 获取所有匹配的key
        Set<String> keys = (Set<String>) redisCache.keys("0_cookie:*");
        // 批量删除
        if (keys != null && !keys.isEmpty()) {
            redisCache.deleteObject(keys);
        }

    }

    public static void main(String[] args) {
        //List<JSONObject> jsonList = new ArrayList<>();
        //JSONObject obj1 = new JSONObject();
        //obj1.put("topic_name", "测试话题\n");
        //obj1.put("status_count", 100);
        //obj1.put("description", "这是一个\n带换行和 空格的\n描述");
        //jsonList.add(obj1);
        //List<MySuperWords> convert = JsonUtils.convert(jsonList, MySuperWords.class);
        //System.out.println(convert);
        System.out.println(DateUtils.getNowToMorningSecond());

    }

}
